<template>
  <a-card>

    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button size="small" type="primary" @click="addCategory(1)">
          <template #icon>
            <PlusOutlined/>
          </template>
          新增一级分类
        </a-button>
        <a-button size="small" type="primary" @click="addCategory(2)">
          <template #icon>
            <PlusOutlined/>
          </template>
          新增二级分类
        </a-button>
        <a-button size="small" type="primary" @click="addCategory(3)">
          <template #icon>
            <PlusOutlined/>
          </template>
          新增三级分类
        </a-button>
      </div>
    </a-row>

    <a-table
        :columns="categoryColumns"
        :dataSource="categoryTableData"
        :loading="categoryTableLoading"
        :pagination="false"
        :scroll="{ x: 1300 }"
        bordered
        childrenColumnName="child"
        rowKey="id"
        size="small"
    >
      <template #bodyCell="{ column, record, text }">

        <template v-if="column.dataIndex === 'typeName'">
          {{ text }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          <span :style="{color: text===0?'#87d068':'#f50'}">{{ text === 0 ? '上架' : '下架' }}</span>
        </template>

        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button type="link" @click="edit(record)">编辑</a-button>
            <a-button danger type="link" @click="confirmDelete(record)">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
          v-model:current="categoryTableQueryForm.pageNum"
          v-model:pageSize="categoryTableQueryForm.pageSize"
          :defaultPageSize="categoryTableQueryForm.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(categoryTableTotal) => `共${categoryTableTotal}条`"
          :total="categoryTableTotal"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="getCategoryTableList"
          @showSizeChange="getCategoryTableList"
      />
    </div>

    <!--  添加和修改对话框-->
    <a-modal :title="`${formData.id?'编辑':'新增'}分类`" :visible="categoryModalVisible" @cancel="categoryModalOnClose"
             @ok="categoryModalSave">
      <a-row v-if="formData.tier!==1" class="row">
        <a-col :span="4" class="rowLabel"><span class="req">*</span>上级分类</a-col>
        <a-col :span="20">
          <a-select v-model:value="formData.parentId"
                    :field-names="{label: 'typeName',value: 'id'}"
                    :options="parentCategoryOptions"
                    @change="parentIdChange"
                    allowClear placeholder="选择分类" style="width: 200px">
          </a-select>
        </a-col>
      </a-row>
      <a-row class="row">
        <a-col :span="4" class="rowLabel"><span class="req">*</span>名称</a-col>
        <a-col :span="20">
          <a-input v-model:value="formData.typeName" :maxlength="20" placeholder="请输入分类名称" show-count
                   style="width: 200px"/>
        </a-col>
      </a-row>

      <a-row class="row">
        <a-col :span="4" class="rowLabel">排序</a-col>
        <a-col :span="20">
          <a-input-number v-model:value="formData.sort" min="0" placeholder="请输入排序"
                          style="width: 200px;margin-right: 8px"/>
          <a-tooltip title="数字越大在同级分类中越靠前">
            <QuestionCircleOutlined/>
          </a-tooltip>
        </a-col>
      </a-row>

      <a-row class="row">
        <a-col :span="4" class="rowLabel"><span class="req">*</span>状态</a-col>
        <a-col :span="20">
          <a-radio-group v-model:value="formData.status">
            <a-radio :value="0">上架</a-radio>
            <a-radio :value="1">下架</a-radio>
          </a-radio-group>
        </a-col>
      </a-row>

    </a-modal>

  </a-card>
</template>

<script setup>

import {onMounted, reactive, ref} from "vue";
import {TABLE_ID_CONST} from "/@/constants/support/table-id-const";
import TableOperator from "/@/components/support/table-operator/index.vue";
import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const";
import FileUpload from "/@/components/support/file-upload/index.vue";
import {mobileCategoryApi} from "/@/views/business/marketing/mobile-category/mobile-category";
import {brandApi} from "/@/views/business/data-config/brand/brand-api";
import {smartSentry} from "/@/lib/smart-sentry";
import {message, Modal} from "ant-design-vue";
import {questionApi} from "/@/views/business/evaluate/question/question-api";
import {PAGE_SIZE, PAGE_SIZE_OPTIONS} from "/@/constants/common-const";
import {SmartLoading} from "/@/components/framework/smart-loading";

const categoryColumns = ref([
  {
    title: '分类名称',
    dataIndex: 'typeName',
    width: 100,
    ellipsis: true,
  },
  {
    title: '分类id',
    dataIndex: 'id',
    align: 'center',
    width: 60,
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    width: 60,
  },
  {
    title: '排序',
    dataIndex: 'sort',
    align: 'center',
    width: 60,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
    width: 60,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    align: 'center',
    width: 60,
  },
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    width: 80,
    fixed: 'right'
  },
]);
const categoryTableData = ref([]);
const categoryTableTotal = ref();
const categoryTableQueryForm = reactive({
  pageNum: 1,
  pageSize: PAGE_SIZE
})
const categoryTableLoading = ref(false);

const categoryModalVisible = ref(false);
const parentCategoryOptions = ref([]);
const formDataDefault = {
  id: undefined,
  typeName: undefined,
  sort: 0,
  parentId: undefined, // 上级id
  pid: undefined, // 第一级id
  tier: 1, // 层级
  status: 1, // 状态 1下架 0上架
}
const formData = reactive({...formDataDefault});

function addCategory(level) {
  formData.tier = level;
  showAddCategoryModal(formData.tier - 1);
}

async function showAddCategoryModal(tier) {
  if (formData.tier === 1) {
    categoryModalVisible.value = true;
    return;
  }
  let responseModel = await mobileCategoryApi.queryByTier({tier});
  if (responseModel.data.length) {
    parentCategoryOptions.value = responseModel.data;
    categoryModalVisible.value = true;
  } else {
    message.error(`没有可选的${formData.tier - 1}级分类`)
  }

}

onMounted(() => {
  getCategoryTableList();
})

async function getCategoryTableList() {
  try {
    categoryTableLoading.value = true;
    let responseModel = await mobileCategoryApi.queryPage(categoryTableQueryForm);
    const list = responseModel.data.list;
    categoryTableData.value = list;
    categoryTableTotal.value = responseModel.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    categoryTableLoading.value = false;
  }
}

function categoryModalOnClose() {
  Object.assign(formData, formDataDefault);
  categoryModalVisible.value = false;
  parentCategoryOptions.value = [];
}

// 删除
function confirmDelete(record) {

  Modal.confirm({
    title: '提示',
    content: '确定要删除【' + record.typeName + '】吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      singleDelete(record);
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

async function singleDelete(brandData) {
  try {
    SmartLoading.show();
    await mobileCategoryApi.delete(brandData.id);
    message.success('删除成功');
    getCategoryTableList();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

function parentIdChange(v, o) {
  if (formData.tier === 3){
    if (v !== undefined) {
      formData.pid = o.pid;
    } else {
      formData.pid = undefined;
    }
  }
  if (formData.tier === 2){
    formData.pid = v;
  }
}

async function edit(record) {
  formData.tier = record.tier;
  await showAddCategoryModal(formData.tier - 1);
  formData.id = record.id;
  formData.parentId = record.parentId || 0;
  formData.pid = record.pid || 0;
  formData.sort = record.sort;
  formData.status = record.status;
  formData.tier = record.tier;
  formData.typeName = record.typeName;
}

async function categoryModalSave() {

  if (!formData.typeName) {
    return message.error('请输入分类名称');
  }
  console.log(formData)
  if (formData.tier !== 1 && !formData.parentId) {
    return message.error('请选择上级分类');
  }

  try {
    if (formData.id) {
      await mobileCategoryApi.update({
        id: formData.id,
        parentId: formData.parentId || 0,
        pid: formData.pid || 0,
        sort: formData.sort,
        status: formData.status,
        tier: formData.tier,
        typeName: formData.typeName
      });
    } else {
      await mobileCategoryApi.add({
        parentId: formData.parentId || 0,
        pid: formData.pid || 0,
        sort: formData.sort,
        status: formData.status,
        tier: formData.tier,
        typeName: formData.typeName
      });
    }
    message.success(`${formData.id ? '修改' : '添加'}成功`)
    categoryModalOnClose();
    getCategoryTableList();
  } catch (e) {
    smartSentry.captureError(e);
  }
}

</script>

<style lang="less" scoped>
.row {
  margin-bottom: 8px;
  align-items: center;

  .rowLabel {
    text-align: right;
    padding-right: 8px;

    .req {
      color: red;
    }
  }
}
</style>